package com.wwj.tem.exception;

import cn.dev33.satoken.exception.DisableServiceException;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.hutool.core.date.BetweenFormatter;
import cn.hutool.core.date.DateUtil;
import com.wwj.tem.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: wwj
 * @create: 2024/7/24 - 21:58
 * Description:
 */
@Slf4j
@RestControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
	
	@ExceptionHandler(BusinessException.class)
	public Result businessExceptionHandler(BusinessException e) {
		log.error("发生业务异常！ msg: ->", e);
		return Result.error(e.getMessage());
	}
	
	// 在当前类每个方法进入之前触发的操作
	@ModelAttribute
	public void get(HttpServletRequest request) throws IOException {
	
	}
	
	// 全局异常拦截（拦截项目中的所有异常）
	@ExceptionHandler
	public Result handlerException(Exception e, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 不同异常返回不同状态码
		Result result = null;
		if (e instanceof NotLoginException) { // 如果是未登录异常
			NotLoginException ee = (NotLoginException) e;
			result = Result.getNotLogin().setMsg(ee.getMessage());
		} else if (e instanceof NotRoleException) { // 如果是角色异常
			NotRoleException ee = (NotRoleException) e;
			result = Result.getNotJur("无此角色：" + ee.getRole());
		} else if (e instanceof NotPermissionException) { // 如果是权限异常
			NotPermissionException ee = (NotPermissionException) e;
			result = Result.getNotJur("无此权限：" + ee.getPermission());
		} else if (e instanceof DisableServiceException) { // 如果是被封禁异常
			DisableServiceException ee = (DisableServiceException) e;
			// 使用 DateUtil.formatBetween() 格式化时长为：x天x小时x分x秒
			result = Result.getDisable("此账号已被封禁：" + DateUtil.formatBetween(ee.getDisableTime() * 1000, BetweenFormatter.Level.SECOND) + "后解封");
		} else {
			result = Result.error(e.getMessage());
		}
		return result;
	}
}
